<template>
    <el-row>
        <el-row style="border-bottom: 1px gray dotted;padding-bottom:10px">
            指令组: 
            <exSelect v-model="selGroup" :dictList="cmdList" @change="refreshList" size="mini" elstyle="width:140px"></exSelect>
            <exInput v-model="selGroupInfo.name" label="组名" size="mini" width="100"></exInput>
            <el-button size="mini" type="primary" @click="addGroup()">增加</el-button>
            <el-button size="mini" type="primary" @click="delGroup()">删除</el-button>
            <el-button size="mini" type="primary" @click="setDefGroup()">设为默认</el-button>
            <!-- <el-button size="mini" type="primary" @click="addCmd()">保存</el-button> -->

            <el-button size="mini" type="warning" @click="saveConfig" style="float:right" class="mr10">保存指令</el-button>
        </el-row>
        <el-row class="mt5" v-if="selGroupInfo.value">
            <el-button size="mini" type="primary" @click="setChildHide(false)">展开全部</el-button>
            <el-button size="mini" type="primary" @click="setChildHide(true)">收起全部</el-button>
            <el-button size="mini" type="primary" @click="addCmd()" :title="`执行次数: ${tmpCount}`">增加指令</el-button>
            <el-button size="mini" type="success" v-if="!isRuning" @click="runCmd()">执行指令</el-button>
            <el-button size="mini" type="warning" v-else @click="stopCmd()">中断指令</el-button>
            

            <el-popover placement="bottom" width="360" trigger="click" style="float:right" class="mr10">
                <exInput v-model="importTxt" type="textarea" :rows="10" width="350"></exInput>
                <div style="text-align: right;" class="mt10">
                    <el-button type="primary" size="mini" @click="doImport">导入</el-button>
                </div>
                <el-button size="mini" type="success" slot="reference">导入指令</el-button>
            </el-popover>
            <el-button size="mini" type="success" @click="copyConfig" style="float:right" class="mr10">复制指令到剪切板</el-button>

            
        </el-row>
        <el-row style="overflow-y:auto;max-height:600px;" >
            <div :style="cmdListStyle" ref="cmdListDiv" class="miniinput">
                <template v-if="isShowCmds">
                    <cmdList ref="cmdList" :cmdList="selGroupInfo.cmds" :devInfo="devInfo" @changeRunStatus="changeRunStatus"></cmdList>
                    <!-- <cmditem v-for="(item,idx) in selGroupInfo.cmds" :key="idx" :cmdInfo="item" :cmdIdx="idx" :cmdList="selGroupInfo.cmds"
                        :devInfo="devInfo" :ref="'cmd'+idx" @delCmd="delCmd" @changeLevel="changeLevel"></cmditem> -->
                </template>
            </div>
        </el-row>
    </el-row>
</template>


<script>

import cmditem from "./cmditem"
import cmdList from "./cmdList"
import canvasCmp from "./cmd/util/canvasCmp.vue"

export default {
    props:{
        isBatch:{default:false},
        devInfo:{},
        defCfg: {},
    },
    components:{
        cmditem,
        cmdList,
        canvasCmp
    },
    data() {
        return {
            tmpCount : 0,
            cmdList : [],
            cfg: this.defCfg || {},
            isRuning : false ,
            selGroup : "",
            defCmd : [
                {name:"小米有品-茅台",value:"234234234",cmds:[
                    {"type":"stopApp","appPath":"com.xiaomi.youpin","x1":0,"y1":0,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":5,children:[]},
                    {"type":"openApp","appPath":"com.xiaomi.youpin","x1":0,"y1":0,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":15,children:[]},
                    {"type":"click","appPath":"","x1":265,"y1":268,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":15,children:[]},
                    {"type":"click","appPath":"","x1":154,"y1":125,"x2":0,"y2":0,children:[]},
                    {"type":"timer","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"timer":"09:59:45",children:[]},
                    {"type":"circle","appPath":"","x1":164,"y1":451,"x2":0,"y2":0,"waitTime":100,"keep":30,children:[]}
                ]},
            ],
            importTxt:"",
            isShowCmds: true,
            cmdListStyle : "",
        };
    },
     

    mounted() {
        this.readConfig()
    },
    computed:{
        selGroupInfo(){
            if(!this.selGroup) return {name:"",value:"",cmds:[]};
            var group =  this.cmdList.find((item)=>{ return item.value==this.selGroup})
            if(!group) return {name:"",value:"",cmds:[]};
            return group
        }
    },
    provide () {
      return {
        doNextCmd: this.runNextCmd,
        refreshList : this.refreshList
      }
    },

    methods: {
        changeRunStatus(isRuning){
            this.isRuning = isRuning? true:false;
        },
        refreshList(){
            this.updateCmds();
            this.isShowCmds = false;
            this.cmdListStyle = this.$refs.cmdListDiv.clientHeight||"";
            this.$nextTick(()=>{
                this.cmdListStyle = "";
                this.isShowCmds = true;
            })
        },
        addGroup(){
            var id = parseInt(Math.random()*100000)+"";
            var group = {name:"新增",value:id,cmds:[]};
            this.selGroup = id;
            this.cmdList.push(group)
        },
        setDefGroup(){
            for(var i=0;i<this.cmdList.length;i++){
                var item = this.cmdList[i];
                if(item.value==this.selGroup){
                    item.isDef = true;
                }else{
                    item.isDef = false;
                }
            }
            this.$message.success("设置成功")
        },
        delGroup(){
            if(!this.selGroup){
                this.$message.error("请选择要删除的组")
                return;
            }
            this.$confirm('确认要删除选中的分组?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var that = this;
                for(var i=0;i<this.cmdList.length;i++){
                    var item = this.cmdList[i];
                    if(item.value==this.selGroup){
                        this.cmdList.splice(i,1);
                        this.selGroup="";
                        break;
                    }
                }
            });
        },
        doImport(){
            try{
                var list = JSON.parse(this.importTxt)
                if(list.length>0){
                    this.selGroupInfo.cmds = list;
                }
            }catch(ex){
                this.$message.error("导入异常:"+ex.message)
            }
        },
        updateCmds(){
            if(this.$refs.cmdList) this.$refs.cmdList.saveCmd()
        },
        copyConfig(){
            this.updateCmds();
            this.copy(JSON.stringify(this.selGroupInfo.cmds))
        },
        saveConfig(){
            this.updateCmds();
            this.cfg.adbCmdCfg.cmdList = this.cmdList;

            this.$confirm('确认要保存记录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var that = this;
                
                this.registerListen(this,"saveConfig",(err)=>{
                    try{
                        if(err){
                            that.$message.error("配置保存异常:"+err)
                        }else{
                            that.$message.success("保存成功")
                        }
                    }catch(ex){
                            that.$message.error("配置保存异常:"+err)
                    }
                });
                
                electron.ipcRenderer.send("saveConfig",this.cfg)
            });
        },
        readConfig(){
            if(this.cfg.adbCmdCfg){
                this.cmdList = this.cfg.adbCmdCfg.cmdList;
                if(this.cmdList.length>0){
                    var group = this.cmdList.find((item)=>{return item.isDef===true})
                    if(!group) this.selGroup = this.cmdList[0].value
                    else this.selGroup = group.value;
                    this.cmdList.map(item=>{
                        if(!item.children) item.children = []
                    })
                }
                return;
            }
            var that = this;
            if(!window.electron){
                return;
            }
            this.registerListen(this,"setConfig",(cfg)=>{
                try{
                    cfg.adbCmdCfg = cfg.adbCmdCfg || {};
                    cfg.adbCmdCfg.cmdList = cfg.adbCmdCfg.cmdList || that.defCmd;
                    if(cfg.adbCmdCfg.cmdList.length>0){
                        if(!cfg.adbCmdCfg.cmdList[0].value){
                            var item = {name:"默认分组",value:"defCmd",cmds:cfg.adbCmdCfg.cmdList};
                            cfg.adbCmdCfg.cmdList = [item]
                        }
                    }
                    that.cmdList = cfg.adbCmdCfg.cmdList;
                    if(that.cmdList.length>0){
                        var group = that.cmdList.find((item)=>{return item.isDef===true})
                        if(!group) that.selGroup = that.cmdList[0].value
                        else that.selGroup = group.value;
                        that.cmdList.map(item=>{
                            if(!item.children) item.children = []
                        })
                    }
                    that.cfg = cfg;
                }catch(ex){
                    that.$message.error("配置加载异常:"+ex.message)
                }
            });
            electron.ipcRenderer.send("getConfig","")

        },
        setChildHide(isHide){
            this.loopCmd(this.selGroupInfo.cmds,(item)=>{
                if(item.children.length>0)
                    item.hideChild = isHide;
            });
            this.refreshList();
        },
        loopCmd(list,cb){
            list.map(item=>{
                if(cb) cb(item);
                if(item.children){
                    this.loopCmd(item.children,cb)
                }
            })
        },
        stopCmd(){
            this.$refs.cmdList.stopCmd();
        },
        addCmd(){
            this.$refs.cmdList.addCmd();
        },
        runCmd(){
            if(this.$refs.cmdList){
                this.$refs.cmdList.initCmd()
                this.$refs.cmdList.runCmd()
            }
        },
        changeDev(){
            var tmp =JSON.parse(this.devInfoBak)
            Object.assign(this.devInfo,tmp)
            this.connectStatus = 0;
            if(this.device) this.getDeviceInfo();
        },
    }
}
</script>
<style lang="less">

.miniinput{
    .el-input{
        input{
            padding-right: 2px;
            padding-left: 2px;
            border-left: 0px;
            border-top: 0px;
            border-right:0px;
        }
        
        .el-input__icon{
            display: none !important;
        }
    }
    .el-select{
        
        .el-input{

            input{
                padding-right: 5px;
                padding-left: 5px;
                border-left: 1px solid #DCDFE6;
                border-top: 1px solid #DCDFE6;
                border-right:1px solid #DCDFE6;
            }
            
            .el-input__icon{
                display: inline-block !important;
            }
        }
    }
}
</style>

<style lang="less" scoped>

.block{
    min-height: 400px;
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    overflow-x: true;
    // border: 1px red solid;

    .devInfo{
        border-right: 1px gray dotted;
        height:100%;
    }
    .devImg{
        text-align: center;
        border-right: 1px gray dotted;
        // background: lightblue;
    }
}

</style>
